package com.zima.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zima.mall.entity.MallShoppingCartItem;
import com.zima.mall.entity.MallUser;
import com.zima.mall.mapper.CartMapper;
import com.zima.mall.mapper.LoginInformationMapper;
import com.zima.mall.service.CartService;
import com.zima.mall.vo.CartVo;
import com.zima.mall.vo.TableVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Resource
    private CartMapper cartMapper;

    @Resource
    private LoginInformationMapper loginInformationMapper;

    @Override
    public TableVo findAllByAccount(String account) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account",account);
        MallUser mallUser = loginInformationMapper.selectOne(wrapper);

        TableVo<CartVo> cartVoTableVo = new TableVo<>();
        List<CartVo> cart = cartMapper.findAllById(mallUser.getUserId());

        cartVoTableVo.setTotalNum(cart.size());
        cartVoTableVo.setData(cart);

        return cartVoTableVo;
    }

    @Override
    public Integer delById(Integer id) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id",id);
        int num = 0;
        num = cartMapper.delete(wrapper);
        return num;
    }

    @Override
    public Integer add(String account, Integer productId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account",account);
        MallUser mallUser = loginInformationMapper.selectOne(wrapper);
        int beAffectedNum = 0;

        UpdateWrapper updateWrapper = new UpdateWrapper();
        Map<String ,Object> map = new HashMap<>();
        map.put("user_id",mallUser.getUserId());
        map.put("product_id",productId);
        updateWrapper.allEq(map);

        if (cartMapper.selectCount(updateWrapper) != 0){//如果已经存在该条目，则只需要给对应条目商品数量加1
            int quantity = cartMapper.selectOne(updateWrapper).getQuantity();
            updateWrapper.set("quantity",quantity + 1);
            beAffectedNum = cartMapper.update(null,updateWrapper);
        }
        else {
            MallShoppingCartItem mallShoppingCartItem = new MallShoppingCartItem();
            mallShoppingCartItem.setProductId(productId);
            mallShoppingCartItem.setUserId(mallUser.getUserId());
            mallShoppingCartItem.setQuantity(1);

            beAffectedNum = cartMapper.insert(mallShoppingCartItem);
        }
        return beAffectedNum;
    }
}
